﻿'© 2004 - 2009 ActiveModules, Inc. All Rights Reserved
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <ToolboxData("<{0}:forumdisplay runat=server></{0}:forumdisplay>")> _
    Public Class ForumDisplay
        Inherits ControlsBase
#Region "Private Members"
        'Dim pt As Forums.Utils.TimeCalcItem
        Private _forumGroupId As Integer = -1
        Private _toggleBehavior As Integer = 0
#End Region
#Region "Public Properties"
        Public Property ToggleBehavior() As Integer
            Get
                Return _toggleBehavior
            End Get
            Set(ByVal value As Integer)
                _toggleBehavior = value
            End Set
        End Property
#End Region
#Region "Event Handlers"
        'Dim sb As New StringBuilder
        'Dim fl As New ForumCollection
        'Dim db As New Data.Forums
        '    fl = db.Forums_List(PortalId, ModuleId, UserId, String.Empty)

        '    For Each f As Forum In fl
        '        sb.Append(f.ForumName)
        '        sb.Append("<br />")
        '    Next
        '    writer.Write(sb.ToString)
        Private Sub ForumDisplay_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            Dim sTemp As String = String.Empty
            'pt = New Forums.Utils.TimeCalcItem("ForumDisplay")

            Dim obj As Object = DataCache.CacheRetrieve(ModuleId & ForumGroupId & "fvt")
            If obj Is Nothing Then
                sTemp = ParseTemplate()
            Else
                sTemp = CType(obj, String)
            End If
            sTemp = Utilities.LocalizeControl(sTemp)
            If Not sTemp.Contains(Globals.ControlRegisterAFTag) Then
                sTemp = Globals.ControlRegisterAFTag & sTemp
            End If
            Dim ctl As Control = Page.ParseControl(sTemp)
            LinkControls(ctl.Controls)
            Me.Controls.Add(ctl)



        End Sub
        Private Sub ForumDisplay_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        End Sub
        Private Sub ForumDisplay_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            ' pt.ProcEnd("ForumDisplay")
        End Sub
#End Region
#Region "Private Methods"
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                If TypeOf ctrl Is Controls.ForumRow Then
                    DirectCast(ctrl, Controls.ForumRow).UserRoles = ForumUser.UserRoles
                End If
                If TypeOf ctrl Is Controls.ControlsBase Then
                    DirectCast(ctrl, Controls.ControlsBase).ControlConfig = Me.ControlConfig
                    DirectCast(ctrl, Controls.ControlsBase).ModuleConfiguration = Me.ModuleConfiguration
                End If
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
        Private Function ParseTemplate() As String
            Dim sb As New StringBuilder
            Dim groupTemplate As String = DisplayTemplate
            If groupTemplate.Contains("[GROUPSECTION]") Then
                groupTemplate = TemplateUtils.GetTemplateSection(DisplayTemplate, "[GROUPSECTION]", "[/GROUPSECTION]")
            End If
            Dim db As New Data.ForumsDB
            ForumData = db.ForumListXML(ControlConfig.SiteId, ControlConfig.InstanceId)
            If Not ForumData Is Nothing Then
                Dim xGroups As System.Xml.XmlNodeList
                If ForumGroupId = -1 Then
                    xGroups = ForumData.SelectNodes("//groups/group[@active='true']")
                Else
                    xGroups = ForumData.SelectNodes("//groups/group[@groupid='" & ForumGroupId & "' and @active='true']")
                End If

                For Each xNode As System.Xml.XmlNode In xGroups
                    Dim sGroup As String = groupTemplate
                    Dim groupId As Integer = Integer.Parse(xNode.Attributes("groupid").Value.ToString)
                    Dim groupName As String = xNode.Attributes("name").Value.ToString
                    sGroup = sGroup.Replace("[GROUPNAME]", groupName)
                    Dim isVisible As Boolean = True
                    If ToggleBehavior = 1 Then
                        isVisible = False
                    End If
                    sGroup = sGroup.Replace("[GROUPCOLLAPSE]", "<af:toggle IsVisible=""" & isVisible & """  id=""tgGroup" & groupId & """ key=""" & groupId & """ cssclass=""afarrow"" CssClassOn=""aficon afarrowdown"" CssClassOff=""aficon afarrowleft"" runat=""server"" ImagePath=""" & ThemePath & """ />")
                    Dim xNodeList As System.Xml.XmlNodeList = ForumData.SelectNodes("//forums/forum[@active='true' and @groupid='" & groupId & "' and @parentforumid='0']")
                    Dim forums As New StringBuilder
                    Dim i As Integer = 0
                    For Each fNode As System.Xml.XmlNode In xNodeList
                        i += 1
                        Dim sCSSClass As String = "afforumrowmid"
                        If i = 1 Then
                            sCSSClass = "afforumrowtop"
                        ElseIf i = xNodeList.Count Then
                            sCSSClass = "afforumrowbottom"
                        End If
                        Dim fid As Integer = Integer.Parse(fNode.Attributes("forumid").Value.ToString)
                        'Dim viewRoles As String = fNode.Attributes("canview").Value.ToString
                        'Dim readRoles As String = fNode.Attributes("canread").Value.ToString
                        Dim sForum As String = TemplateUtils.GetTemplateSection(sGroup, "[FORUMS]", "[/FORUMS]")
                        sForum = sForum.Replace("[CSS:ROWCLASS]", sCSSClass)
                        sForum = ParseForumRow(fNode, sForum, groupName)

                        forums.Append(sForum)
                    Next

                    sGroup = TemplateUtils.ReplaceSubSection(sGroup, forums.ToString, "[FORUMS]", "[/FORUMS]")
                    sGroup = sGroup.Replace("[GROUP]", "<af:toggledisplay IsVisible=""" & isVisible & """ id=""tgdGroup" & groupId & """ key=""" & groupId & """ runat=""server""><content>")
                    sGroup = sGroup.Replace("[/GROUP]", "</content></af:toggledisplay>")
                    sb.Append(sGroup)
                Next
            End If
            Dim sOut As String = sb.ToString
            If sOut.Contains("[GROUPSECTION]") Then
                sOut = TemplateUtils.ReplaceSubSection(DisplayTemplate, sb.ToString, "[GROUPSECTION]", "[/GROUPSECTION]")
            End If

            'sOut = sOut.Replace("[BREADCRUMB]", String.Empty)
            'sOut = sOut.Replace("[WHOSONLINE]", "<af:usersonline id=""ctlUsersOnline"" templatefile=""usersonline.htm"" runat=""server"" />")
            'sOut = sOut.Replace("[JUMPTO]", String.Empty)
            'sOut = sOut.Replace("[TEMPLATE:TOOLBAR]", "<af:toolbar id=""ctlToolbar"" templatefile=""toolbar.htm"" runat=""server"" />")

            'DataCache.CacheStore(ModuleId & "fvt", sOut)
            Return sOut
        End Function
        Private Function ParseForumRow(ByVal fNode As XmlNode, ByVal Template As String, ByVal GroupName As String) As String
            Dim sForum As String = Template

            Dim lasttopicid As Integer = 0
            Dim lastreplyid As Integer = 0
            Dim fid As Integer = 0
            Dim lastpostdate As String = fNode.Attributes("lastpostdate").Value.ToString
            Dim lastReadDate As Date = Date.Parse(fNode.Attributes("lastread").Value.ToString)
            Dim viewRoles As String = fNode.Attributes("viewroles").Value.ToString
            Dim readRoles As String = fNode.Attributes("readroles").Value.ToString
            Dim forumname As String = fNode.Attributes("name").Value.ToString
            Dim hidden As String = fNode.Attributes("hidden").Value.ToString
            lasttopicid = Integer.Parse(fNode.Attributes("lasttopicid").Value.ToString)
            lastreplyid = Integer.Parse(fNode.Attributes("lastreplyid").Value.ToString)



            fid = Integer.Parse(fNode.Attributes("forumid").Value.ToString)
            'TODO: Validate can view
            'sForum = sForum.Replace("[FORUMNAME]", "<af:link id=""hypForumName" & fid & """ navigateurl=""" & Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & fid}) & """ text=""" & forumname & """ runat=""server"" />") 'GetForumLink(forumname, PageId, True))
            sForum = sForum.Replace("[FORUMNAME]", "<af:link id=""hypForumName" & fid & """ navigateurl=""" & URL.ForForum(PageId, fid, String.Empty, forumname) & """ text=""" & forumname & """ runat=""server"" />") 'GetForumLink(forumname, PageId, True))
            sForum = sForum.Replace("[FORUMNAMENOLINK]", forumname)
            sForum = sForum.Replace("[FORUMDESCRIPTION]", fNode.Attributes("desc").Value.ToString)
            sForum = sForum.Replace("[TOTALTOPICS]", fNode.Attributes("totaltopics").Value.ToString)
            sForum = sForum.Replace("[TOTALREPLIES]", fNode.Attributes("totalreplies").Value.ToString)
            sForum = sForum.Replace("[DISPLAYNAME]", fNode.Attributes("lastpostauthorname").Value.ToString)
            sForum = sForum.Replace("[LASTPOST]", "<asp:placeholder id=""plhLastPost" & fid & """ runat=""server"">")
            sForum = sForum.Replace("[/LASTPOST]", "</asp:placeholder>")


            Dim intLength As Integer = 0
            If InStr(sForum, "[LASTPOSTSUBJECT:") > 0 Then
                Dim inStart As Integer = InStr(sForum, "[LASTPOSTSUBJECT:") + 17
                Dim inEnd As Integer = InStr(inStart, sForum, "]")
                Dim sLength As String = sForum.Substring(inStart - 1, inEnd - inStart)
                intLength = CType(sLength, Integer)
            End If
            Dim ReplaceTag As String = "[LASTPOSTSUBJECT:" & intLength.ToString & "]"
            Dim sSubject As String = fNode.Attributes("lastpostsubject").Value.ToString
            If lastreplyid = 0 Then
                lastreplyid = lasttopicid
            End If
            sSubject = GetLastPostSubject(lastreplyid, lasttopicid, fid, sSubject, intLength)

            sForum = sForum.Replace(ReplaceTag, sSubject)
            If sSubject = String.Empty Then
                sForum = sForum.Replace("[RESX:BY]", String.Empty)
                sForum = sForum.Replace("[LASTPOSTDATE]", String.Empty)
            Else
                sForum = sForum.Replace("[LASTPOSTDATE]", lastpostdate)
            End If
            'TODO: Properly check "canview"
            Dim sIcon As String = TemplateUtils.ShowIcon(True, fid, UserId, Date.Parse(lastpostdate), lastReadDate, lastreplyid)
            Dim sIconImage As String = "<img alt=""" & forumname & """ src=""" & ThemePath & "images/" & sIcon & """ />"
            sForum = sForum.Replace("[FORUMICON]", sIconImage)
            sForum = sForum.Replace("[CSS:FORUMICON]", "affoldernorm")
            sForum = sForum.Replace("[CSS:FORUMICONSM]", "affoldersmnorm")
            sForum = sForum.Replace("[FORUMICONSM]", sIconImage.Replace("folder", "folder16"))
            Dim xNodeList As System.Xml.XmlNodeList = ForumData.SelectNodes("//forums/forum[@active='true' and @parentforumid='" & fid & "']")
            Dim sSubs As String = String.Empty
            If xNodeList.Count > 0 Then
                Dim sTemplate As String = TemplateUtils.GetTemplateSection(Template, "[SUBFORUMS]", "[/SUBFORUMS]")
                For Each n As XmlNode In xNodeList
                    sSubs &= ParseForumRow(n, sTemplate, GroupName)
                Next
            End If
            sForum = TemplateUtils.ReplaceSubSection(sForum, sSubs, "[SUBFORUMS]", "[/SUBFORUMS]")
            Dim fc As String = "<af:forumrow id=""ctlFR" & fid & """ Hidden=""" & hidden & """ ForumId=""" & fid & """ ReadRoles=""" & readRoles & """ ViewRoles=""" & viewRoles & """ runat=""server"">"
            fc &= "<content>" & sForum & "</content>"
            fc &= "</af:forumrow>"
            Return fc
        End Function
        Private Function GetForumLink(ByVal ForumId As Integer, ByVal CanView As Boolean) As String
            Return GetForumLink(String.Empty, ForumId, CanView)
        End Function
        Private Function GetForumLink(ByVal Name As String, ByVal ForumId As Integer, ByVal CanView As Boolean) As String
            Dim sOut As String
            sOut = Name
            Dim Params() As String = {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & ForumId}
            If CanView And Not Name = String.Empty Then
                sOut = "<a href=""" & Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & ForumId}) & """>" & Name & "</a>"
            ElseIf CanView And Name = String.Empty Then
                Return Utilities.NavigateUrl(PageId, "", Params)
            Else
                sOut = Name
            End If
            Return sOut
        End Function
#End Region
#Region "Public Methods"
        Private Function GetLastPostSubject(ByVal LastPostID As Integer, ByVal ParentPostID As Integer, ByVal fid As Integer, ByVal Subject As String, ByVal Length As Integer) As String
            Dim sOut As String = String.Empty
            Dim PostId As Integer = LastPostID
            Subject = Utilities.StripHTMLTag(Subject)
            Subject = Subject.Replace("[", "&#91")
            Subject = Subject.Replace("]", "&#93")
            If Not LastPostID = 0 Then
                If Subject.Length > Length Then
                    Subject = Subject.Substring(0, Length) & "..."
                End If
                Dim sURL As String = String.Empty
                If ParentPostID = 0 Or LastPostID = ParentPostID Then
                    sURL = Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ForumId & "=" & fid, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & PostId})
                Else
                    sURL = Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ForumId & "=" & fid, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & ParentPostID, ParamKeys.ContentJumpId & "=" & PostId})

                End If
                sOut = "<af:link id=""hypLastPostSubject" & fid & """ NavigateUrl=""" & sURL & """ Text=""" & DotNetNuke.Modules.ActiveForums.Utilities.HTMLEncode(Subject) & """ runat=""server"" />"
            End If
            Return sOut
        End Function
#End Region




    End Class
End Namespace

